package com.resume.aipeople.config;

import com.resume.aipeople.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                    // 公开接口
                    .antMatchers("/api/auth/**").permitAll()
                    .antMatchers("/api/characters/**").permitAll()
                    .antMatchers("/api/model/**").permitAll()
                    .antMatchers("/api/voice/**").permitAll()
                    .antMatchers("/api/audio/**").permitAll()
                    .antMatchers("/h2-console/**").permitAll()
                    .antMatchers("/", "/index.html", "/static/**", "/js/**", "/css/**", "/images/**", "/mp4/**", "/favicon.ico").permitAll()
                    // 需要认证的接口
                    .antMatchers("/api/chat/**").authenticated()
                    .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        // 允许H2控制台的iframe
        http.headers().frameOptions().disable();
    }
}
